<template>
  <el-card style="height: 80px;">
    <el-form :inline="true" class="search_form" ref="form">
      <el-form-item label="职位搜索">
        <el-input v-model="keyword" placeholder="请输入搜索用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="keyword ? false : true" type="primary" @click="search">搜索</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px;">
    <el-button type="primary" icon="Plus" @click="addRole">添加职位</el-button>
    <el-table :data="allRole" border style="margin: 10px 0px;">
      <el-table-column type="index" label="#" align="center"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column label="职位名称" show-overflow-tooltip align="center" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" show-overflow-tooltip align="center" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" show-overflow-tooltip align="center" prop="updateTime"></el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template #="{ row, $index }">
          <el-button type="primary" size="small" icon="User" @click="setPermission(row)">分配权限</el-button>
          <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
          <el-popconfirm :title="`你确定要删除${row.roleName}吗`" width="260px" @confirm="removeRole(row.Id)">
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
      layout=" prev, pager, next, jumper,->,sizes,total" :total="total" :background="true" @current-change="getHasRole"
      @size-change="sizeChange" />
  </el-card>
  <!-- 更新|添加职位 -->
  <el-dialog v-model="dialogVisite" :title="RoleParams.id ? '更新职位' : '添加职位'">
    <el-form ref="form" label-width="100px" :model="RoleParams" :rules="rules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input placeholder="请你输入职位名称" v-model="RoleParams.roleName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="dialogVisite = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件：分配用户职位的菜单权限与按钮权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮权限</h4>
    </template>
    <template #default>
      <!-- 树形控件 -->
      <el-tree ref="tree" style="max-width: 600px" :data="menuArr" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="selectArr" :props="defaultProps" />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang='ts' name='role'>
import { reqAllRoleList, reqAddOrUpdateRole, reqAllMenuList, reqSetPermisstion, reqRemoveRole } from '@/api/acl/role';
import type { Records, RoleResponseData, RoleData, MenuResponseData, MenuList } from '@/api/acl/role/type';
import { nextTick, onMounted, reactive, ref } from 'vue';
import useLayOutSettingStore from '@/store/modules/setting';
import { ElMessage } from 'element-plus';
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
//用户总个数
let total = ref<number>(0)
let keyword = ref<string>('')
let allRole = ref<Records>([])
let layOutSettingStore = useLayOutSettingStore()
//对话框的显示与隐藏
let dialogVisite = ref<boolean>(false)
//新增岗位对象
let RoleParams = reactive<RoleData>({
  roleName: '',
})
//获取表单组件实例
let form = ref<any>()
onMounted(() => {
  getHasRole()
})
//控制抽屉的显示与隐藏
let drawer = ref<boolean>(false)
//存储用户权限数组
let menuArr = ref<MenuList>([])
//分配职位相关数据
//想展示的数据叫什么名字
const defaultProps = {
  children: 'children',
  label: 'name',
}
//准备一个数组：数组用于存储勾选的节点id(最后一级的)
let selectArr = ref<number[]>([])
//树形组件数组
let tree = ref<any>()
// -----------------------------------------------------------------------------------------
//获取全部已有的用户信息
const getHasRole = async (pager = 1) => {

  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
  if (result.code == 200) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}
const sizeChange = () => {
  getHasRole()
}
const search = () => {
  getHasRole()
  keyword.value = ""
}
const reset = () => {
  layOutSettingStore.refsh = !layOutSettingStore.refsh
}
const addRole = () => {
  //清空输入框数据
  Object.assign(RoleParams, {
    roleName: '',
    id: 0
  })
  //清空表单校验结果
  nextTick(() => {
    form.value.clearValidate("roleName")
  })
  dialogVisite.value = true

}
const updateRole = (row: RoleData) => {
  dialogVisite.value = true
  //存储已有职位
  Object.assign(RoleParams, row)
  //清空表单校验结果
  nextTick(() => {
    form.value.clearValidate("roleName")
  })
}
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}
//职位校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }]
}
//确定按钮回调
const save = async () => {
  //表单结果通过才发请求
  await form.value.validate()
  //添加职位|更新职位|
  let result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: RoleParams.id ? '更新成功' : '添加成功' })
    dialogVisite.value = false
    getHasRole(RoleParams.id ? pageNo.value : 1)
  } else {
    ElMessage({ type: 'error', message: RoleParams.id ? '更新失败' : '添加失败' })
    dialogVisite.value = false
  }
}
//分配权限按钮回调
const setPermission = async (row: RoleData) => {
  //抽屉展示
  drawer.value = true
  //收集当前要分类权限的职位的数据
  Object.assign(RoleParams, row)
  //根据职位获取权限的数据
  let result: MenuResponseData = await reqAllMenuList((row.id as number))
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
//筛选勾选中的最后一级权限
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.children.length == 0 && item.select) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
//分配权限确定按钮
const handler = async () => {
  //职位id
  const roleId = (RoleParams.id as number)
  //选中节点id
  let arr = tree.value.getCheckedKeys();
  //办选的ID
  let arr1 = tree.value.getHalfCheckedKeys();
  let permissionId = arr.concat(arr1)
  let result: any = await reqSetPermisstion(roleId, permissionId)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({ type: 'success', message: '分配权限成功' })
    window.location.reload()
  }
}
//删除角色
const removeRole = async (roleId:number) => {
  let result :any = reqRemoveRole(roleId)
  if(result.code == 200){
    ElMessage({type:'success',message:'删除角色成功'})
    getHasRole(allRole.value.length >1 ? pageNo.value: 1)
  }else{
    ElMessage({type:'error',message:'删除角色失败'})
  }
}




</script>


<style scoped>
.search_form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>